package com.dayuanit.dy16.atm.service.impl;

import com.dayuanit.dy16.atm.entity.User;
import com.dayuanit.dy16.atm.entity.WxBind;
import com.dayuanit.dy16.atm.exception.BizException;
import com.dayuanit.dy16.atm.handler.EmailHandler;
import com.dayuanit.dy16.atm.mapper.UserMapper;
import com.dayuanit.dy16.atm.mapper.WxBindMapper;
import com.dayuanit.dy16.atm.service.IUserService;
import com.dayuanit.dy16.atm.vo.ForgetPwdRequestVO;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserServiceImpl implements IUserService {

    public UserServiceImpl() {
        System.out.println("UserServiceImpl()");
    }

    @Autowired
    private UserMapper userMapper;

    @Value("${atm.password.salt}")
    private String passwordSalt;

    @Autowired
    private EmailHandler emailHandler;

    @Autowired
    private WxBindMapper wxBindMapper;

    @Override
    public void signUp(String username, String pwd, String confirmPwd) {

        if (StringUtils.isBlank(username) || StringUtils.isBlank(pwd) || StringUtils.isBlank(confirmPwd)) {
            throw new BizException("有必填参数为空");
        }

        if (!pwd.equals(confirmPwd)) {
            throw new BizException("两次输入的密码不相等");
        }

        // 校验用户名是否重复
        User user = userMapper.getByUsername(username);
        if (null != user) {
            throw new BizException("用户名已存在");
        }

        //密码的明文 盐值：username
        //明文=pwd+username
        pwd = pwd + username;

        //MD5之后的密文
        String signPwd = DigestUtils.md5Hex(pwd);

        user = new User();
        user.setCreateTime(new Date());
        user.setPassword(signPwd);
        user.setUsername(username);
        userMapper.insert(user);
    }

    @Override
    public User login(String username, String pwd) {
        if (StringUtils.isBlank(username) || StringUtils.isBlank(pwd)) {
            throw new BizException("有必填参数为空");
        }

        User user = userMapper.getByUsername(username);
        if (null == user){
            throw new BizException("用户名不存在或密码错误");
        }

        //明文=pwd+username
        pwd = pwd + username;

        String signPwd = DigestUtils.md5Hex(pwd);

        if (!signPwd.equals(user.getPassword())) {
            throw new BizException("用户名不存在或密码错误");
        }

        return user;
    }

    @Override
    public void bindEmail(long userId, String email) {
        if (StringUtils.isBlank(email)) {
            throw new BizException("请输入邮箱");
        }

        User user = userMapper.getByEmail(email);
        if (user != null) {
            throw new BizException("邮箱已绑定");
        }

        emailHandler.sendActiveEmail(email, user.getId());
    }

    @Override
    public void activeEmail(long userId, String email, String sign, long endTime) {
        if (StringUtils.isBlank(email) || StringUtils.isBlank(sign)) {
            throw new BizException("激活失败");
        }

        if (System.currentTimeMillis() > endTime) {
            throw new BizException("激活失败");
        }

        String tempSign = DigestUtils.md5Hex(email + userId + passwordSalt + endTime);
        if (!sign.equals(tempSign)) {
            throw new BizException("激活失败");
        }

        userMapper.updateEmail(userId, email);
    }

    @Override
    public void changePasword(String password, String confirmPassword, ForgetPwdRequestVO forgetPwdRequestVO) {
        if (StringUtils.isBlank(password) || StringUtils.isBlank(confirmPassword)
                || StringUtils.isBlank(forgetPwdRequestVO.getEmail()) || StringUtils.isBlank(forgetPwdRequestVO.getSign())) {
            throw new BizException("非法请求");
        }

        if (!password.equals(confirmPassword)) {
            throw new BizException("两次密码不相等");
        }

        if (System.currentTimeMillis() > forgetPwdRequestVO.getEndTime()) {
            throw new BizException("请求已过期，请重新操作");
        }

        // 校验签名
        String sign = DigestUtils.md5Hex(forgetPwdRequestVO.getEmail() + passwordSalt + forgetPwdRequestVO.getEndTime());
        if (!sign.equals(forgetPwdRequestVO.getSign())) {
            throw new BizException("非法请求");
        }

        User user = userMapper.getByEmail(forgetPwdRequestVO.getEmail());

        password = password + user.getUsername();
        int rows = userMapper.updatePassword(user.getId(), DigestUtils.md5Hex(password));
        if (1 != rows) {
            throw new BizException("密码修改失败");
        }
    }

    @Override
    public void sendForgetEmail(String email) {
        if (StringUtils.isBlank(email)) {
            throw new BizException("请输入邮箱");
        }

        emailHandler.sendResetPassword(email);
    }

    @Override
    public void wxBind(String openId, String nickName, User user) {
        //绑定微信和ATM账号
        WxBind wxBind = new WxBind();
        wxBind.setCreateTime(new Date());
        wxBind.setNickName(nickName);
        wxBind.setOpenId(openId);
        wxBind.setUserId(user.getId());
        wxBindMapper.insert(wxBind);
    }

    @Override
    public WxBind getWxBind(String openId) {
        return wxBindMapper.getByOpenId(openId);
    }

    @Override
    public User getUser(long userId) {
        return userMapper.selectByPrimaryKey(userId);
    }
}
